package priv.pront.code.national.acwing.base;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class A844_走迷宫 {

    static char[][] g;
    static boolean[][] v;
    static int[] dx = {-1,1,0,0}, dy = {0,0,-1,1};
    static Queue<int[]> queue = new LinkedList<>();
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        g = new char[n][m];
        v = new boolean[n + 1][m + 1];
        scanner.nextLine();
        for(int i = 0; i < n; i++) g[i] = scanner.nextLine().replaceAll(" ","").toCharArray();
        int[] cur = {0 ,0, 0};
        queue.add(cur);
        while(!queue.isEmpty()){
            cur = queue.poll();
            if(cur[0] == n - 1 && cur[1] == m - 1){
                System.out.println(cur[2]);
                break;
            }
            for(int i = 0; i < 4; i++) {
                int x = cur[0] + dx[i];
                int y = cur[1] + dy[i];
                if (x >= 0 && y >= 0 && x < n && y < m && !v[x][y] && g[x][y] == '0') {
                    v[x][y] = true;
                    queue.add(new int[]{x, y, cur[2] + 1});
                }
            }
        }
    }
}
